﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

using Microsoft.Xna.Framework.Media;

namespace Coding4Fun.SlideShow
{
    public partial class AlbumListItem : UserControl
    {
        public event SelectedPictureEventHandler PictureSelected;
        public delegate void SelectedPictureEventHandler(object sender, EventArgs e);

        /// <summary>
        /// A list of possible visual states to randomly choose from
        /// </summary>
        private readonly List<string> _states = new List<string>();

        /// <summary>
        /// UserControl Contructor
        /// </summary>
        public AlbumListItem()
        {
            // Required to initialize variables
            InitializeComponent();

            // Addes the various states that the Album List Item could have
            _states.Add("TopLeft");
            _states.Add("TopRight");
            _states.Add("BottomLeft");
            _states.Add("BottomRight");

            // Goes to a random state
            VisualStateManager.GoToState(this, _states[App.RandomNumber.Next(0, _states.Count)], false);
        }

        private PictureAlbum _album;
        /// <summary>
        /// Gets or Sets the album to display in the list.
        /// Creates a thumbnail in within the list taking pictures from the album while also setting the album name
        /// </summary>
        public PictureAlbum Album
        {
            get { return _album; }
            set
            {
                _album = value;

                // Sets album name
                uxLabel.Text = Album.Name;

                // Puts together thumbnail collage
                var count = 1;

                foreach (var pic in Album.Pictures)
                {
                    if (count > 3)
                        break;

                    var img = FindName("uxImage" + count) as Image;

                    var bitmap = new BitmapImage();

                    using (var source = pic.GetThumbnail())
                        bitmap.SetSource(source);

                    if (img != null)
                        img.Source = bitmap;

                    count++;
                }
            }
        }

        private void LayoutRoot_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			if (PictureSelected != null)
			{
				e.Handled = true;
				App.SelectedAlbum = _album.Pictures;

				PictureSelected.Invoke(this, null);
			}
		}
    }
}
